#include "LivingEntity.h"
#include "Logic/State/StateMachine.h"
#include "Message/MessagePump.h"
#include "Logic/State/State.h"


void ChangeStateCallback::function(void* parent, Message* msg)
{
	int newState = ((DataMessage<int>*)msg)->m_dataStorage;
	((LivingEntity*)parent)->GetStateMachine()->SetGoalID(newState);
}

void GetAttackCallback::function(void* parent, Message* msg)
{
	LogicMsg data;
	data.time = ((LivingEntity*)parent)->GetAttribute().walkSpeed * 20;
	data.direction = ((LivingEntity*)parent)->GetDirection();
	DataMessage<LogicMsg>* newMsg = new DataMessage<LogicMsg>(MODULE_MSG|BROADCAST_MSG, MSGTYPE_ENTITY_HURT,data);
	newMsg->m_toID = ((LivingEntity*)parent)->GetID();
	s_MessagePump->SendMsg(newMsg);
}

LivingEntity::LivingEntity(ENTITYTYPE type,Visual* pVisual):BaseGameEntity(type,pVisual)
{
	m_direction = DIRECTION_DOWN;
	m_pStateMachine = new StateMachine(this);
	s_MessagePump->RegisterForMessage(ENTITY_MSG, MSGTYPE_CHANGE_STATE,this,GetID(),m_changeStateCallback);
	s_MessagePump->RegisterForMessage(ENTITY_MSG, MSGTYPE_ENTITY_HURT,this,GetID(),m_getAtkCallback);
}

StateMachine* LivingEntity::GetStateMachine() const
{
	return m_pStateMachine;
}

void LivingEntity::AddState(State* pState)
{
	m_pStateMachine->AddState(pState);
}

void LivingEntity::SetDirection(DIRECTION dir)
{
	m_direction = dir;
}

void LivingEntity::SetDirection(int dx, int dy)
{
	if (dx > 0)
	{
		if (dy > 0)
		{
			SetDirection(DIRECTION_RDOWN);
		}
		else if (dy == 0)
		{
			SetDirection(DIRECTION_RIGHT);
		}
		else
		{
			SetDirection(DIRECTION_RUP);
		}
	}
	else if (dx == 0)
	{
		if (dy > 0)
		{
			SetDirection(DIRECTION_DOWN);
		}
		else if (dy == 0)
		{
			return;
		}
		else
		{
			SetDirection(DIRECTION_UP);
		}
	}
	else
	{
		if (dy > 0)
		{
			SetDirection(DIRECTION_LDOWN);
		}
		else if (dy == 0)
		{
			SetDirection(DIRECTION_LEFT);
		}
		else
		{
			SetDirection(DIRECTION_LUP);
		}
	}
}

Attribute& LivingEntity::GetAttribute()
{
	return m_attribute;
}

DIRECTION LivingEntity::GetDirection() const
{
	return m_direction;
}